package online.afeibaili.storebackendframework.model.json

import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.type.CollectionType


/**
 * json映射抽象类
 *
 *@author AfeiBaili
 *@version 2025/10/25 21:53
 */

abstract class JsonMapperAbstract<T>(val clazz: Class<T>) {
    open fun toListJson(list: List<T>): String {
        return ObjectMapper().writeValueAsString(list)
    }

    open fun toListObject(jsonObjects: String): MutableList<T> {
        val collectionType: CollectionType =
            ObjectMapper().typeFactory.constructCollectionType(MutableList::class.java, clazz)
        val list = runCatching {
            ObjectMapper().readValue<MutableList<T>>(jsonObjects, collectionType)
        }.getOrElse { exception ->
            exception.printStackTrace()
            mutableListOf()
        }
        return list
    }

    open fun toJson(t: T): String {
        return ObjectMapper().writeValueAsString(t)
    }

    open fun toObject(jsonObject: String): T {
        return ObjectMapper().readValue(jsonObject, clazz)
    }
}